package org.cfx.gift.exception.handler;


import org.cfx.gift.exception.BusinessException;
import org.cfx.gift.exception.code.ResponseCode;
import org.cfx.gift.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理类
 */
@RestControllerAdvice   // 在执行controller方法的前/后执行某个逻辑
public class GlobalExeptionHandler {

    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        // 捕获到BusinessException以后,要将错误信息返回给前端
        // 业务异常错误码应该是要由BusinessException进行传递,而不能在这块写死
        return AjaxResult.me().setCode(e.getCode()).setSuccess(false).setMessage(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        // 获取jsr303配置的错误信息
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuffer sb = new StringBuffer();
        for (ObjectError allError : allErrors) {
            sb.append(allError.getDefaultMessage());
            sb.append(",");
        }
        return AjaxResult.me().setCode(ResponseCode.RESPONSE_CODE_400.getCode()).setSuccess(false).setMessage(sb.substring(0,sb.length()-1));
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        // 捕获到BusinessException以后,要将错误信息返回给前端
        return AjaxResult.me().setCode(ResponseCode.RESPONSE_CODE_500.getCode()).setSuccess(false).setMessage(ResponseCode.RESPONSE_CODE_500.getMessage());
    }
}
